package com.dpiinc.TechPage.user.setting;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.dpiinc.TechPage.BaseActivity;
import com.dpiinc.TechPage.R;
import com.dpiinc.TechPage.UserManager;
import com.dpiinc.TechPage.api.BaseObserver;
import com.dpiinc.TechPage.api.RetrofitFactory;
import com.dpiinc.TechPage.api.RxSchedulers;
import com.dpiinc.TechPage.model.BaseEntity;
import com.dpiinc.TechPage.model.jbean.BaseBean;
import com.dpiinc.TechPage.pen.dialog.ProgressDialog;
import com.dpiinc.TechPage.user.utils.ToastUtils;
import com.dpiinc.TechPage.widget.ClearEditText;

import java.util.HashMap;

import androidx.annotation.Nullable;
import io.reactivex.Observable;

/**
 * Created by hu489_000 on 2018-06-25.
 */

public class FeedBackActivity extends BaseActivity {

    private static final String TAG = "FeedBackActivity";
    private boolean isEnable;
    EditText projectName;
    ClearEditText edit_telphone;
    private LinearLayout mLlRoot;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        setContentView(R.layout.feed_back);
        super.onCreate(savedInstanceState);

        setBackWhite();
        setstatusBarColor(R.color.color_00bad2);

        projectName = (EditText) findViewById(R.id.editText_feedback);
        mLlRoot = (LinearLayout) findViewById(R.id.ll_root);
        projectName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(s)) {
                    isEnable = false;
                } else {
                    isEnable = true;
                }
                invalidateOptionsMenu();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        edit_telphone = (ClearEditText) findViewById(R.id.edit_telphone);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_feed_back, menu);
        menu.getItem(0).setEnabled(isEnable);
        MenuItem item = menu.findItem(R.id.menu_feed_back);
        SpannableString spannableString = new SpannableString(item.getTitle());
        if (isEnable) {
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.clear_note_dialog_btn_text_color_left)), 0, spannableString.length(), 0);
        } else {
            spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.color_7386b1)), 0, spannableString.length(), 0);
        }
        item.setTitle(spannableString);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case R.id.menu_feed_back:
                feedBack(FeedBackActivity.this);
                break;
            default:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 提交用户反馈
     *
     * @param context
     */
    private void feedBack(final Context context) {

        isEnable = false;
        invalidateOptionsMenu();
        projectName.postDelayed(new Runnable() {
            @Override
            public void run() {
                isEnable = true;
                invalidateOptionsMenu();
            }
        }, 5000);

//        ToastUtils.showFeedSubmittingCenterTip(FeedBackActivity.this);
        ProgressDialog.ShowDialog(FeedBackActivity.this);

        new Handler().postDelayed(new Runnable() {
            public void run() {
                //execute the task

                HashMap<String, String> requestMap = getFeedBackMap();
                Observable<BaseEntity<BaseBean>> observable = RetrofitFactory.getInstance().feedBack(requestMap);
                BaseObserver mBaseObserver = new BaseObserver<BaseBean>(context) {
                    @Override
                    protected void onHandleError(int code) {
                        super.onHandleError(code);
                        Log.d(TAG, "onHandleError code = " + code);
                        ProgressDialog.dismissDialog();
                        ToastUtils.showTopTip(FeedBackActivity.this, getString(R.string.feed_back_fail));
                    }

                    @Override
                    protected void onHandleSuccess(BaseBean baseBean) {
                        // 保存用户信息等操作
                        ProgressDialog.dismissDialog();
                        Log.d(TAG, "onHandleSuccess baseBean = " + baseBean);
                        ToastUtils.showFeedOkCenterTip(FeedBackActivity.this);
                        projectName.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                closeInput();
                                finish();
                            }
                        }, 2000);

                    }
                };
                observable.compose(RxSchedulers.compose()).subscribe(mBaseObserver);
            }
        }, 1000);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        closeInput();
        finish();
    }

    /**
     * 按关键字搜索
     */
    private HashMap<String, String> getFeedBackMap() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("uId", UserManager.INSTANCE.getUserId());
        params.put("accessToken", UserManager.INSTANCE.getAccessToken());
        params.put("opinion", projectName.getText().toString());
        params.put("contact", edit_telphone.getText().toString());
        params.put("appVersion", getVersionName(this));
        params.put("appPlatform", "Android-" + getDeviceBrand() + "-" + getSystemModel() + "-" + getSystemVersion());
        return params;
    }

    //版本名
    public static String getVersionName(Context context) {
        return getPackageInfo(context).versionName;
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;
        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pi;
    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 获取当前手机系统版本号
     *
     * @return 系统版本号
     */
    public static String getSystemVersion() {
        return android.os.Build.VERSION.RELEASE;
    }


    private void closeInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
//            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            inputMethodManager.hideSoftInputFromWindow(FeedBackActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(mLlRoot.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
}
